/*
 * Copyright (C) 1994-2021 Altair Engineering, Inc.
 * For more information, contact Altair at www.altair.com.
 *
 * This file is part of both the OpenPBS software ("OpenPBS")
 * and the PBS Professional ("PBS Pro") software.
 *
 * Open Source License Information:
 *
 * OpenPBS is free software. You can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * OpenPBS is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Commercial License Information:
 *
 * PBS Pro is commercially licensed software that shares a common core with
 * the OpenPBS software.  For a copy of the commercial license terms and
 * conditions, go to: (http://www.pbspro.com/agreement.html) or contact the
 * Altair Legal Department.
 *
 * Altair's dual-license business model allows companies, individuals, and
 * organizations to create proprietary derivative works of OpenPBS and
 * distribute them - whether embedded or bundled with other software -
 * under a commercial license agreement.
 *
 * Use of Altair's trademarks, including but not limited to "PBS™",
 * "OpenPBS®", "PBS Professional®", and "PBS Pro™" and Altair's logos is
 * subject to Altair's trademark licensing policies.
 */

/**
 *
 * @brief
 *	The Submit Job request.
 */

#include <pbs_config.h> /* the master config generated by configure */

#include <stdio.h>
#include <strings.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include "libpbs.h"
#include "credential.h"
#include "pbs_ecl.h"
#include "pbs_client_thread.h"

#include "ticket.h"

/* for use with pbs_submit_with_cred */
struct cred_info {
	int cred_type;
	size_t cred_len;
	char *cred_buf;
};

/**
 * @brief
 *	-wrapper function for pbs_submit where submission takes credentials.
 *
 * @param[in] c - communication handle
 * @param[in] attrib - pointer to attr list
 * @param[in] script - script to be submitted
 * @param[in] destination - host where submission happens
 * @param[in] extend - extend string for encoding req
 * @param[in] credtype - credential type
 * @param[in] credlen - credential length
 * @param[in] credbuf - buffer to hold cred info
 *
 * @return 	string
 * @retval	jobid	success
 * @retval	NULL	error
 *
 */
char *
pbs_submit_with_cred(int c, struct attropl *attrib, char *script,
		     char *destination, char *extend, int credtype,
		     size_t credlen, char *credbuf)
{
	char *ret;
	struct pbs_client_thread_context *ptr;
	struct cred_info *cred_info;

	/* initialize the thread context data, if not already initialized */
	if (pbs_client_thread_init_thread_context() != 0)
		return NULL;

	/* lock pthread mutex here for this connection */
	/* blocking call, waits for mutex release */
	if (pbs_client_thread_lock_connection(c) != 0)
		return NULL;

	ptr = (struct pbs_client_thread_context *) pbs_client_thread_get_context_data();
	if (!ptr) {
		pbs_errno = PBSE_INTERNAL;
		(void) pbs_client_thread_unlock_connection(c);
		return NULL;
	}

	if (!ptr->th_cred_info) {
		cred_info = malloc(sizeof(struct cred_info));
		if (!cred_info) {
			pbs_errno = PBSE_INTERNAL;
			(void) pbs_client_thread_unlock_connection(c);
			return NULL;
		}
		ptr->th_cred_info = (void *) cred_info;
	} else
		cred_info = (struct cred_info *) ptr->th_cred_info;

	/* copy credentials to static variables */
	cred_info->cred_buf = credbuf;
	cred_info->cred_len = credlen;
	cred_info->cred_type = credtype;

	/* pbs_submit takes credentials from static variables */
	ret = pbs_submit(c, attrib, script, destination, extend);

	cred_info->cred_buf = NULL;
	cred_info->cred_len = 0;
	cred_info->cred_type = 0;

	/* unlock the thread lock and update the thread context data */
	if (pbs_client_thread_unlock_connection(c) != 0)
		return NULL;

	return ret;
}

/**
 * @brief
 *	-submit job request
 *
 * @param[in] c - communication handle
 * @param[in] attrib - ponter to attr list
 * @param[in] script - job script
 * @param[in] dest - host where job submitted
 * @param[in] extend - buffer to hold cred info
 *
 * @return      string
 * @retval      jobid   success
 * @retval      NULL    error
 *
 */
char *
__pbs_submit(int c, struct attropl *attrib, const char *script, const char *dest, const char *extend)
{
	struct attropl *pal;
	char *return_jobid = NULL;
	int rc;
	struct pbs_client_thread_context *ptr;
	struct cred_info *cred_info = NULL;
	int commit_done = 0;
	char *lextend = NULL;

	/* initialize the thread context data, if not already initialized */
	if ((pbs_errno = pbs_client_thread_init_thread_context()) != 0)
		goto error;

	ptr = (struct pbs_client_thread_context *) pbs_client_thread_get_context_data();
	if (!ptr) {
		pbs_errno = PBSE_INTERNAL;
		goto error;
	}

	/* first verify the attributes, if verification is enabled */
	if (pbs_verify_attributes(c, PBS_BATCH_QueueJob, MGR_OBJ_JOB, MGR_CMD_NONE, attrib) != 0)
		goto error; /* pbs_errno is already set in this case */

	/* lock pthread mutex here for this connection */
	/* blocking call, waits for mutex release */
	if (pbs_client_thread_lock_connection(c) != 0)
		goto error; /* pbs_errno is already set in this case */

	/* first be sure that the script is readable if specified ... */
	if ((script != NULL) && (*script != '\0')) {
		if (access(script, R_OK) != 0) {
			pbs_errno = PBSE_BADSCRIPT;
			if (set_conn_errtxt(c, "cannot access script file") != 0)
				pbs_errno = PBSE_SYSTEM;
			goto error;
		}
	}

	/* initiate the queueing of the job */
	for (pal = attrib; pal; pal = pal->next)
		pal->op = SET; /* force operator to SET */

	cred_info = (struct cred_info *) ptr->th_cred_info;
	if ((!script || (*script == '\0')) && (!cred_info || (cred_info->cred_len <= 0))) {
		/* no cred and no script, let's request implicit commit to cut one message exchange */
		if (extend) {
			lextend = EXTEND_OPT_IMPLICIT_COMMIT;
			if (!pbs_strcat(&lextend, NULL, extend)) {
				if (set_conn_errtxt(c, "Failed to allocate memory") != 0)
					pbs_errno = PBSE_SYSTEM;
				lextend = NULL;
				goto error;
			}
			extend = lextend;
		} else
			extend = EXTEND_OPT_IMPLICIT_COMMIT;
	}

	/* Queue job with null string for job id */
	return_jobid = PBSD_queuejob(c, "", dest, attrib, extend, PROT_TCP, NULL, &commit_done);
	if (return_jobid == NULL)
		goto error;

	if (commit_done)
		goto done;

	/* send script across */
	if ((script != NULL) && (*script != '\0')) {
		if ((rc = PBSD_jscript(c, script, 0, NULL)) != 0) {
			if (rc == PBSE_JOBSCRIPTMAXSIZE)
				pbs_errno = rc;
			else
				pbs_errno = PBSE_BADSCRIPT;
			goto error;
		}
	}

	/* OK, the script got across, apparently, so we are */
	/* ready to commit */
	/* opaque information */
	if (cred_info && cred_info->cred_len > 0) {
		if (PBSD_jcred(c, cred_info->cred_type,
			       cred_info->cred_buf,
			       cred_info->cred_len, 0, NULL) != 0) {
			pbs_errno = PBSE_BADCRED;
			goto error;
		}
	}

	if (PBSD_commit(c, return_jobid, 0, NULL, NULL) != 0)
		goto error;

error:
done:
	free(lextend);
	/* unlock the thread lock and update the thread context data */
	pbs_client_thread_unlock_connection(c);
	return return_jobid;
}
